package com.tangx.search.listener;


import com.alibaba.fastjson.JSON;
import com.tangx.common.constants.ArticleConstants;
import com.tangx.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Optional;

/**
 * 同步文章数据到ES的MQ监听器
 */
@Component
@Slf4j
public class ApArticleSynEsListener {

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void pollMsg(ConsumerRecord<String,String> consumerRecord){
        Optional<ConsumerRecord<String, String>> optional = Optional.ofNullable(consumerRecord);
        optional.ifPresent(x->{
            log.info("[文章同步ES监听器]开始执行");
            SearchArticleVo searchArticleVo = JSON.parseObject(x.value(), SearchArticleVo.class);

            IndexRequest indexRequest = new IndexRequest("app_info_article");
            indexRequest.source(JSON.toJSONString(searchArticleVo), XContentType.JSON).id(searchArticleVo.getId().toString());
            try {
                IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
                log.info("[文章同步ES监听器]文章导入ES响应结果： {}", indexResponse.status() );
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("[文章同步ES监听器]执行结束" );
        });
    }
}
